<template>
  <div>
    <el-button type="primary" icon="el-icon-upload2" size="medium" class="custom-file-upload" @click="triggerFileInput">
      {{ buttonText }}
      <input type="file" id="file-upload" @change="onFileChange" accept=".xlsx" style="display: none;" />
    </el-button>
    <p v-if="message" :class="{ 'success': isSuccess, 'error': !isSuccess }">{{ message }}</p>
  </div>
</template>

<script>
export default {
  props: {
    initialButtonText: {
      type: String,
      default: '选择并上传文件'
    }
  },
  data() {
    return {
      selectedFile: null,
      message: '',
      isSuccess: false,
      buttonText: this.initialButtonText
    };
  },
  methods: {
    triggerFileInput() {
      document.getElementById('file-upload').click();
    },
    onFileChange(event) {
      this.selectedFile = event.target.files[0];
      if (this.selectedFile) {
        this.buttonText = this.selectedFile.name;
        this.uploadFile();
      }
    },
    async uploadFile() {
      const formData = new FormData();
      formData.append('file', this.selectedFile);

      try {
        const res = await this.$http.post('bookKeeping/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: localStorage.getItem("token")
          }
        });
        if (res.status === 200) {
          this.$message.success(res.data);
          this.message = res.data;
          this.isSuccess = true;
          this.resetFileInput();
          console.log('File uploaded successfully, emitting file-uploaded event');

          this.$emit('file-uploaded'); // 触发自定义事件
        } else {
          this.$message.error(res.data);
          this.message = res.data;
          this.isSuccess = false;
          this.resetFileInput();
        }
      } catch (error) {
        console.error('Error uploading file:', error);
        this.$message.error('上传失败: ' + error.response.data);
        this.message = '上传失败: ' + error.response.data;
        this.isSuccess = false;
        this.resetFileInput();
      }
    },
    resetFileInput() {
      const fileInput = document.getElementById('file-upload');
      fileInput.value = ''; // 重置文件输入框
      this.selectedFile = null; // 重置选中的文件
      this.message = ''; // 清空消息
      this.isSuccess = false; // 重置成功状态
      this.buttonText = this.initialButtonText; // 恢复初始文本
    }
  }
};
</script>

<style scoped>
/* 自定义样式 */
.custom-file-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
}

.custom-file-upload input[type="file"] {
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.success {
  color: green;
}

.error {
  color: red;
}
</style>
